import router from "@/router";
import { useLoginUserStore } from "@/store/userStore";
import AccessEnum from "@/access/accessEnum";
import checkAccess from "@/access/checkAccess";

router.beforeEach(async (to, from, next) => {
  const loginUserStore = useLoginUserStore();

  let currentUser = loginUserStore.user;
  const needAccess = to.meta?.access ?? AccessEnum.NOT_LOGIN;
  // 如果当前没有用户信息，就从后端获取用户信息
  if (!currentUser || !currentUser.userRole) {
    await loginUserStore.fetchLoginUser();
    //重新赋值
    currentUser = loginUserStore.user;
  }
  if (needAccess != AccessEnum.NOT_LOGIN) {
    //没登录
    if (!currentUser) {
      next(`/user/login?redirect${to.fullPath}`);
    }
    if (!checkAccess(currentUser, needAccess)) {
      next("/user/login");
      return;
    }
  }
  next();
});
